package com.example.demo_dongruanD.service.impl;

import com.example.demo_dongruanD.dto.InsertCiDetailedReportRequest;
import com.example.demo_dongruanD.dto.SetMealDetailDto;
import com.example.demo_dongruanD.pojo.*;
import com.example.demo_dongruanD.repository.*;
import com.example.demo_dongruanD.response.ApiResponse;
import com.example.demo_dongruanD.service.SetMealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class SetMealServiceImpl implements SetMealService {

    @Autowired
    private OrdersRepository ordersRepository;

    @Autowired
    private SetmealRepository setmealRepository;

    @Autowired
    private SetMealDetailedRepository setMealDetailedRepository;

    @Autowired
    private CheckItemRepository checkItemRepository;

    @Autowired
    private CheckItemDetailedRepository checkItemDetailedRepository;

    @Autowired
    private CiDetailedReportRepository ciDetailedReportRepository;

    @Autowired
    public SetMealServiceImpl(SetmealRepository setmealRepository) {
        this.setmealRepository = setmealRepository;
    }

    @Override
    public SetMealDetailDto getSetMealDetail(Integer orderId) {
        Orders order = ordersRepository.findById(orderId).orElse(null);
        if (order == null) {
            return new SetMealDetailDto(404, "Order not found", null);
        }

        Integer smId = order.getSmId();
        Setmeal setmeal = setmealRepository.findById(smId).orElse(null);
        if (setmeal == null) {
            return new SetMealDetailDto(404, "Set meal not found", null);
        }

        List<SetMealDetailed> setMealDetails = setMealDetailedRepository.findBySmId(smId);
        List<Integer> ciIds = setMealDetails.stream().map(SetMealDetailed::getCiId).collect(Collectors.toList());

        // 根据ciId获取checkItemName
        Map<Integer, String> checkItemNames = ciIds.stream()
                .collect(Collectors.toMap(ciId -> ciId, ciId -> {
                    CheckItem checkItem = checkItemRepository.findById(ciId).orElse(null);
                    return checkItem != null ? checkItem.getCiName() : null;
                }));

        // 根据ciId获取详细数据
        Map<Integer, List<SetMealDetailDto.CheckItemDetailedData>> checkItemDetailsMap = ciIds.stream()
                .collect(Collectors.toMap(ciId -> ciId, ciId -> checkItemDetailedRepository.findByCiId(ciId).stream()
                        .map(detail -> {
                            SetMealDetailDto.CheckItemDetailedData detailData = new SetMealDetailDto.CheckItemDetailedData();
                            detailData.setCdId(detail.getCdId());
                            detailData.setName(detail.getName());
                            detailData.setUnit(detail.getUnit());
                            detailData.setMinrange(detail.getMinrange());
                            detailData.setMaxrange(detail.getMaxrange());
                            detailData.setNormalValue(detail.getNormalValue());
                            detailData.setNormalValueString(detail.getNormalValueString()); // 设置 normalValueString
                            detailData.setType(detail.getType()); // 设置 type
                            return detailData;
                        }).collect(Collectors.toList())));

        // 构建checkItems列表
        List<SetMealDetailDto.CheckItem> checkItems = ciIds.stream().map(ciId -> {
            SetMealDetailDto.CheckItem checkItem = new SetMealDetailDto.CheckItem();
            checkItem.setCheckItemName(checkItemNames.get(ciId));
            checkItem.setCheckItemDetails(checkItemDetailsMap.get(ciId));
            return checkItem;
        }).collect(Collectors.toList());

        SetMealDetailDto.SetMealData data = new SetMealDetailDto.SetMealData();
        data.setSetMealName(setmeal.getName());
        data.setCheckItems(checkItems);

        return new SetMealDetailDto(200, "Success", data);
    }

    //查看报告
//    @Override
//    public SetMealDetailDto getSetMealDetail(Integer orderId) {
//        Orders order = ordersRepository.findById(orderId).orElse(null);
//        if (order == null) {
//            return new SetMealDetailDto(404, "Order not found", null);
//        }
//
//        Integer smId = order.getSmId();
//        Setmeal setmeal = setmealRepository.findById(smId).orElse(null);
//        if (setmeal == null) {
//            return new SetMealDetailDto(404, "Set meal not found", null);
//        }
//
//        List<SetMealDetailed> setMealDetails = setMealDetailedRepository.findBySmId(smId);
//        List<Integer> ciIds = setMealDetails.stream().map(SetMealDetailed::getCiId).collect(Collectors.toList());
//
//        // 获取每个ciId对应的详细数据，同时处理value和isError可能为null的情况
//        Map<Integer, List<CiDetailedReport>> ciDetailsMap = ciIds.stream()
//                .collect(Collectors.toMap(Function.identity(), ciId -> ciDetailedReportRepository.findByCiIdAndOrderId(ciId, orderId)));
//
//        // 构建CheckItemDetailedData，注意处理null值
//        List<SetMealDetailDto.CheckItem> checkItems = ciIds.stream().map(ciId -> {
//            SetMealDetailDto.CheckItem checkItem = new SetMealDetailDto.CheckItem();
//            checkItem.setCheckItemName(getCheckItemName(ciId)); // 假设有一个方法来获取名称
//            checkItem.setCheckItemDetails(ciDetailsMap.getOrDefault(ciId, Collections.emptyList()).stream()
//                    .map(detail -> {
//                        SetMealDetailDto.CheckItemDetailedData detailData = new SetMealDetailDto.CheckItemDetailedData();
//                        detailData.setCdId(detail.getCidrId());
//                        detailData.setName(detail.getName());
//                        detailData.setUnit(detail.getUnit());
//                        detailData.setMinrange(detail.getMinrange() != null ? detail.getMinrange().toString() : "");
//                        detailData.setMaxrange(detail.getMaxrange() != null ? detail.getMinrange().toString() : "");
//                        detailData.setNormalValue(detail.getNormalValue());
//                        detailData.setNormalValueString(detail.getNormalValueString());
//                        detailData.setType(detail.getType()!= null ? detail.getType().toString() : "");
//                        detailData.setValue(detail.getValue() != null ? detail.getValue() : "");
//                        detailData.setIsError(detail.getIsError() != null ? detail.getIsError() : Integer.valueOf(""));
//                        return detailData;
//                    })
//                    .collect(Collectors.toList()));
//            return checkItem;
//        }).collect(Collectors.toList());
//
//        SetMealDetailDto.SetMealData data = new SetMealDetailDto.SetMealData();
//        data.setSetMealName(setmeal.getName());
//        data.setCheckItems(checkItems);
//
//        return new SetMealDetailDto(200, "Success", data);
//    }
//    // 获取检查项名称
//    private String getCheckItemName(Integer ciId) {
//        Optional<CheckItem> optionalCheckItem = checkItemRepository.findByCiId(ciId);
//        return optionalCheckItem.map(CheckItem::getCiName)
//                .orElse("Check Item Not Found"); // 如果没有找到，返回默认提示
//    }
    @Override
    public ApiResponse<String> insertCiDetailedReport(InsertCiDetailedReportRequest request) {
        Integer orderId = request.getOrderId();
        List<Integer> cdIds = request.getCdIds();
        List<String> values = request.getValues();
        List<Integer> isErrorList = request.getIsError(); // 获取 isError 字段的数组

        // Find orderId in Orders to get smId
        Orders order = ordersRepository.findById(orderId).orElse(null);
        if (order == null) {
            return new ApiResponse<>(400, "Order not found", null);
        }

        Integer smId = order.getSmId();

        // Find all SetMealDetailed records with matching smId
        List<SetMealDetailed> setMealDetailedList = setMealDetailedRepository.findBySmId(smId);

        // Extract ciIds from SetMealDetailed records
        List<Integer> ciIds = setMealDetailedList.stream()
                .map(SetMealDetailed::getCiId)
                .collect(Collectors.toList());

        // Find CheckItemDetailed records matching ciIds
        List<CheckItemDetailed> checkItemDetailedList = checkItemDetailedRepository.findByCiIdIn(ciIds);

        // Insert records into CiDetailedReport
        for (int i = 0; i < cdIds.size(); i++) {
            Integer cdId = cdIds.get(i);
            String value = values.get(i);
            Integer isError = isErrorList.get(i); // 获取每项的 isError 值

            // Find matching CheckItemDetailed record for cdId
            CheckItemDetailed checkItemDetailed = checkItemDetailedList.stream()
                    .filter(detail -> detail.getCdId().equals(cdId))
                    .findFirst()
                    .orElse(null);

            if (checkItemDetailed != null) {
                CiDetailedReport ciDetailedReport = new CiDetailedReport();
                ciDetailedReport.setName(checkItemDetailed.getName());
                ciDetailedReport.setUnit(checkItemDetailed.getUnit());
                ciDetailedReport.setMinrange(checkItemDetailed.getMinrange());
                ciDetailedReport.setMaxrange(checkItemDetailed.getMaxrange());
                ciDetailedReport.setNormalValue(checkItemDetailed.getNormalValue());
                ciDetailedReport.setNormalValueString(checkItemDetailed.getNormalValueString());
                ciDetailedReport.setValue(value);
                ciDetailedReport.setIsError(isError); // 设置 isError 值
                ciDetailedReport.setType(checkItemDetailed.getType()); // 设置 type 值
                ciDetailedReport.setCiId(checkItemDetailed.getCiId());
                ciDetailedReport.setOrderId(orderId);

                // Save to repository
                ciDetailedReportRepository.save(ciDetailedReport);
            }
        }

        return new ApiResponse<>(200, "Data inserted successfully", null);
    }


    @Override
    public ApiResponse<List<Setmeal>> getAllSetmeals() {
        List<Setmeal> setmealList = setmealRepository.findAll();
        return new ApiResponse<>(200, "查询成功", setmealList);
    }



    /*
    * 以下两个方法是精准查询套餐的接口要用的方法
    * */
    @Override
    public List<Integer> findDistinctSmIdsByDocId(Integer docId) {
        return ordersRepository.findByDocId(docId).stream()
                .map(order -> order.getSmId())
                .distinct()
                .collect(Collectors.toList());
    }

    @Override
    public List<Setmeal> findBySmIds(List<Integer> smIds) {
        return setmealRepository.findBySmIdIn(smIds);
    }
}
